package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.push.PushVo;
import com.sxbbc.common.basics.service.redis.RedisUtilsService;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.CReceivedAddr;
import com.sxbbc.common.core.entity.jz.ChickenCoupon;
import com.sxbbc.common.core.entity.jz.ChickenLogisticsOrder;
import com.sxbbc.common.core.entity.jz.OrderExpDetail;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.ChickenLogisticsOrderMapper;
import com.sxbbc.common.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxbbc.common.core.service.system.pay.ExpService;
import com.sxbbc.common.core.utils.MsgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 物流提鸡 服务实现类
 * </p>
 *
 * @author
 * @since 2020-04-08
 */
@Service
public class ChickenLogisticsOrderServiceImpl extends ServiceImpl<ChickenLogisticsOrderMapper, ChickenLogisticsOrder> implements IChickenLogisticsOrderService {
    @Autowired
    private IPushService pushService;
    @Autowired
    private RedisUtilsService redisUtilsService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private ChickenLogisticsOrderMapper chickenLogisticsOrderMapper;
    @Autowired
    private IOrderExpDetailService orderExpDetailService;
    @Autowired
    private IChickenCouponService iChickenCouponService;
    @Autowired
    private ICReceivedAddrService icReceivedAddrService;
    @Autowired
    private ExpService expService;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    private IBExpConfigService ibExpConfigService;

//    @Override
//    public IPage<ChickenLogisticsOrder> selectChickenLogisticsOrderList(BasePage<ChickenLogisticsOrder> page, ChickenLogisticsOrder chickenLogisticsOrder) {
//        IPage<ChickenLogisticsOrder> logisticsOrderList = chickenLogisticsOrderMapper.selectChickenLogisticsOrderList(page, chickenLogisticsOrder);
//        if (logisticsOrderList.getSize() > 0) {
//            for (ChickenLogisticsOrder record : logisticsOrderList.getRecords()) {
//                record.setOrderStatusName(EnumUtils.getEnum(OrderStatusEnums.class, EnumUtils.GET_ID, record.getOrderStatus()).getName());
//            }
//        }
//        return logisticsOrderList;
//    }

    @Override
    public RestResponse handleOrderDeliver(OrderExpDetail expDetail) {
        //自营店铺 检查order_exp_detail的发货状态
        //如果都已发货，更新order_main的状态
        //否则更新当前ID的状态
        //非自营店铺 直接发货
        boolean save = false;
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //订单
        ChickenLogisticsOrder order = super.getById(expDetail.getOrderId());
        //订单发货单
        OrderExpDetail orderExpDetail = orderExpDetailService.getById(expDetail.getId());

        //自营店检查order_exp_detail表中所有发货状态
        QueryWrapper<OrderExpDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_code", order.getOrderCode()).eq("status", StaticUtils.STATUS_NO).ne("id", expDetail.getId());
        int count = orderExpDetailService.count(wrapper);
        if (count < 1) {
            //订单状态改为发货
            order.setOrderStatus(OrderStatusEnums.HAS_SEND.getId());
        }

        if (calUtil.isEquals(expDetail.getReceivedType(), ReceivedTypeEnums.EXP.getId())) {
            //物流信息表
            orderExpDetail.setExpCode(expDetail.getExpCode());
            orderExpDetail.setExpName(expDetail.getExpName());
            orderExpDetail.setExpNo(expDetail.getExpNo());
        } else {
            QueryWrapper<OrderExpDetail> orderExpDetailQueryWrapper = new QueryWrapper<>();
            orderExpDetailQueryWrapper.eq("order_code", order.getOrderCode())
                    .eq("status", StaticUtils.STATUS_YES).eq("received_type", ReceivedTypeEnums.EXP.getId());
            if (orderExpDetailService.count(orderExpDetailQueryWrapper) == 0) {
                //虚拟发货及自提 直接收货
                order.setOrderStatus(OrderStatusEnums.RECEIVED.getId());
                order.setReceivedTime(LocalDateTime.now());
            }
        }
        order.setSendTime(LocalDateTime.now());
        save = super.updateById(order);
        if (!save) {
            throw new ThrowJsonException("发货失败");
        }
        orderExpDetail.setSign(StaticUtils.STATUS_NO);
        orderExpDetail.setReceivedType(expDetail.getReceivedType());
        orderExpDetail.setSendTime(new Date());
        orderExpDetail.setStatus(StaticUtils.STATUS_YES);
        save = orderExpDetailService.updateById(orderExpDetail);
        if (!save) {
            throw new ThrowJsonException("发货失败");
        }

        //发货成功，将运费结算给商家，需要扣除12个点的平台费
        BigDecimal expMoney = order.getExpMoney();
        if (expMoney.compareTo(new BigDecimal(0)) > 0) {
            BigDecimal businessScale = calUtil.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.BUSINESS_SCALE));
            //平台收益（商家让利）
            BigDecimal scale = calUtil.mul(expMoney, businessScale, 2);
            BigDecimal realMoney = calUtil.sub(expMoney, scale, 2);
            //枚举类缺少，所以注释，本该运行
//            String expmoneyDetail = accountChangeService.insertBMoneyDetail(order.getBid(), HandleTypeEnums.OTHER_RETURN.getId(), StaticUtils.PAY_IN,
//                    order.getPayCode(), realMoney, "运费结算", order.getCid());
//            if (!StringUtils.isEmpty(expmoneyDetail)) {
//                throw new ThrowJsonException("运费结算失败：" + expmoneyDetail);
//            }
        }

        //推送订单发货通知
        String token = redisUtilsService.getKey(order.getCid() + "_token");
        PushVo pushVo = new PushVo(token, MsgUtils.JPUSH_0002, PushTypeEnums.ORDER_NOTICE.getId(),
                order.getOrderCode(), new String[]{order.getOrderCode(), expDetail.getExpNo()}, order.getCid());
        pushService.pushMessageById(pushVo);
        return GetRest.getSuccess("发货成功");
    }

    @Override
    public RestResponse getChickenLogisticsPayInfo(Integer id, Integer cid, Integer addrid) {
        QueryWrapper<ChickenCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", cid).eq("id", id);
        ChickenCoupon chickenCoupon = iChickenCouponService.getOne(queryWrapper);
        if (chickenCoupon == null) {
            return GetRest.getFail("提鸡券不存在");
        }
        //获取收货地址
        CReceivedAddr receivedAddr = null;
        if (addrid == null) {
            //获取默认地址
            receivedAddr = icReceivedAddrService.getDefaultAddr(cid);
        } else {
            receivedAddr = icReceivedAddrService.getById(addrid);
        }
        //获取运费
        BigDecimal exp = expService.getExpByFarm(receivedAddr);
        if(exp.compareTo(new BigDecimal(-1))==0){
            return GetRest.getFail("还未开放物流提鸡哦，请耐心等待");
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("chickenCoupon", chickenCoupon);
        hashMap.put("receivedAddr", receivedAddr);
        hashMap.put("expMoney", exp);
        return GetRest.getSuccess("操作成功", hashMap);
    }
}
